import { Composite } from "matter-js";
import { App } from "./App";
import { LineView } from "./LineView";
import { PotView } from "./PotView";
import { getRandomInt } from "../tooler";

export class ViewMap {
    pot: any = {};
    line: any = {};

    constructor() {

    }

    addData(obj: any) {
        if (Array.isArray(obj)) {
            this.addView(obj);
        }
        else {
            this.addView([obj]);
        }
    }

    addView(items: any[]) {
        const list = items.map((item: any) => {
            return {
                id: item.transactionHash,
                from: item.fromTag || item.address,
                to: item.toTag || item.toAddress,
                origin: item,
            }
        });

        this.addPotView(list);
        this.addLineView(list);
    }

    addPotView(list: any[]) {
        list.forEach(item => {
            if (!this.pot[item.to]) {
                this.addKeyPot(item.to, item.origin.toAddressType)
            }
            if (!this.pot[item.from]) {
                this.addKeyPot(item.from, item.origin.fromAddressType)
            }
        })
    }

    addKeyPot(key: string, type: string) {
        let eoa = type == 'eoa';
        let size = 200;
        let x = getRandomInt(-size, size);
        let y = getRandomInt(-size, size);
        let potView = new PotView(key, x, y, eoa ? 4 : 10, eoa);
        this.pot[key] = potView;
        App.group.add(potView.mesh);
        Composite.add(App.engine.world, [potView.body]);
    }

    addLineView(list: any[]) {
        list.forEach(item => {
            let lineView = new LineView(item.id, this.pot[item.from], this.pot[item.to], 0x606060, item.origin);
            this.line[item.id] = lineView;
            App.group.add(lineView.mesh)
        })
    }

    getHit(obj: any) {
        for (let i in this.pot) {
            if (this.pot[i].mesh == obj) {
                return this.pot[i];
            }
        }
        return null;
    }

    update() {
        for (let i in this.pot) {
            this.pot[i].update();
        }
        for (let i in this.line) {
            this.line[i].update();
        }
    }
}